<?php
namespace app\common\model;

use think\Model;
use think\Db;
use think\Config;
use think\Loader;
class Questions extends Model
{
    // 指定表名,不含前缀
    protected $name = 'questions';

    /**
     * @param null $ids
     */
	 public function tablename()
	{
		return 'ex_'.$this->name;		
	}
    public function getListByIds($ids=null){
        if (is_array($ids) && isset($ids)){
            $ids = implode(',',$ids);
        }
        $child_plaform = getChildAdminRegByPlaformId($this->plaform);
        $condition['id'] = ['in',$ids];
        $questype=Db::name('questions')->field('id,q_typeid,q_question,q_status,q_select,q_answer,q_knowsid,q_qbankid,q_describe')->where($condition)->where(['admin_reg'=>['in',$child_plaform]])->select();
        return $questype;
    }
    public function getList($condition=null){
        $child_plaform = getChildAdminRegByPlaformId($this->plaform);
        $questype=Db::name('questions')->field('id,q_typeid,q_question,q_status,q_select,q_answer,q_knowsid,q_qbankid,q_describe')->where($condition)->where(['admin_reg'=>['in',$child_plaform]])->select();
        return $questype;
    }
    /**
     * 获得章节 ajax
     */
    public function section(){
        $child_plaform = getChildAdminRegByPlaformId($this->plaform);
        $arr=Db::name('sections')->field('id,se_name')->where('se_subjectid', $_POST['pid'])->where(['admin_reg'=>['in',$child_plaform]])->select();
        $arr=json_encode($arr);
        return ajax_return($arr);
    }
    
    public function getQuesListByArg($arg = array(), $limit = 0, $field = '*')
    {
        return $this->where($arg)->field($field)->limit($limit)->select();
    }

    /**
     * 获得科目
     */
    public function subject($id=0){
        $child_plaform = getChildAdminRegByPlaformId($this->plaform);
        if($id){
			if(is_array($id)){
				 $arr=Db::name('subject')->field('id,s_name')->where('isdelete',0)->where(['id'=>['in',$id]])->where(['admin_reg'=>['in',$child_plaform]])->select();
			} else {
            $arr=Db::name('subject')->field('id,s_name')->where('isdelete',0)->where('id',$id)->where(['admin_reg'=>['in',$child_plaform]])->select();
			}
            return $arr;
        }else{
            $arr=Db::name('subject')->field('id,s_name')->where('isdelete',0)->where(['admin_reg'=>['in',$child_plaform]])->select();
            return $arr;
        }
    }
    /**
     * 获得科目
     */
    public function getKnowsList($id=0){
        $child_plaform = getChildAdminRegByPlaformId($this->plaform);
        if($id){
            $arr=Db::name('knows')->field('id,k_name,k_sectionid')->where('isdelete',0)->where('id',$id)->where(['admin_reg'=>['in',$child_plaform]])->select();
            return $arr;
        }else{
            $arr=Db::name('knows')->field('id,k_name,k_sectionid')->where('isdelete',0)->where(['admin_reg'=>['in',$child_plaform]])->select();
            return $arr;
        }
    }

    /**
     * 获得章节
     */
    public function sections($subjectid =0){
        $child_plaform = getChildAdminRegByPlaformId($this->plaform);

        $sqlwhere = ['admin_reg'=>['in',$child_plaform],'status'=>1,'isdelete'=>0];
		/* 增加当有科目ID时，获取对应科目下所有章节 */
		if(!empty($subjectid)){ $sqlwhere['se_subjectid'] = $subjectid; unset($sqlwhere['admin_reg']); }
        $arr=Db::name('sections')->field('id,se_name')->where($sqlwhere)->select();
        return $arr;
    }

    /**
     * 获得知识点
     */
    public function knows(){
        $child_plaform = getChildAdminRegByPlaformId($this->plaform);

        $arr=Db::name('knows')->field('id,k_name')->where('k_sectionid', $_POST['pid'])->where(['admin_reg'=>['in',$child_plaform],'status'=>1,'isdelete'=>0])->select();
        $arr=json_encode($arr);
        return ajax_return($arr);
    }

	/**
     * 获得知识点
     */
    public function getknowsBySectionId($sectionid=0){
        $child_plaform = getChildAdminRegByPlaformId($this->plaform);

        $sqlwhere = ['admin_reg'=>['in',$child_plaform],'status'=>1,'isdelete'=>0];
		/* 增加当有科目ID时，获取对应科目下所有章节 */
		if(empty($sectionid)) $sectionid = $_POST['pid'];
		if(empty($sectionid)) $sectionid = 0;
        $arr=Db::name('knows')->field('id,k_name')->where('k_sectionid', $sectionid)->where($sqlwhere)->select();
		if(empty($arr)){
			unset($sqlwhere['admin_reg']);
			 $arr=Db::name('knows')->field('id,k_name')->where('k_sectionid', $sectionid)->where($sqlwhere)->select();
		}
        
        return $arr;
    }
	
    /**
     * 获得题库
     * @param $id
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function qbank($id){
        $child_plaform = getChildAdminRegByPlaformId($this->plaform);

        if(!$id){
            $arr=Db::name('qbank')->field('id,name')->where('status',1)->where(['admin_reg'=>['in',$child_plaform],'status'=>1,'isdelete'=>0])->select();
        }else{
            $arr=Db::name('qbank')->field('id,name')->where('id',$id)->where('status',1)->where(['admin_reg'=>['in',$child_plaform],'isdelete'=>0])->select();
        }
        return $arr;
    }

    //获取题型列表
    //参数：
    //返回值：题型列表数组
    public function getQuestypeList($args = 1)
    {
        return Db::name('questype')->query("SELECT * FROM agk_questype WHERE 1 LIMIT 512");
    }
    //根据题型ID查询
    //参数：题型ID
    //返回值：题型数组
    public function getQuestypeById($id)
    {
        return Db::name('questype')->query("SELECT * FROM agk_questype WHERE  1 AND id=".$id);
    }
    //根据题型ID查询
    //参数：题型ID
    //返回值：题型数组
    public function getQuesknowsById($id)
    {
        $child_plaform = getChildAdminRegByPlaformId($this->plaform);
        return Db::name('knows')->where(['admin_reg'=>['in',$child_plaform],'id'=>$id])->select();
    }
	
	
	/* 新设计开始 */
	/* 根据知识点ID 获取试题 */
	
	
	public function getQuestionIds($qbankid,$questype=0,$knowsid=0,$num=1)
	{
		
		if($qbankid) $sql_where['q_qbankid'] = $qbankid;
		if($questype) $sql_where['q_typeid'] = $questype;
		if($knowsid) $sql_where['q_knowsid'] = $knowsid;

		$res = Db::name($this->name)->field('id')->where($sql_where)->order('id asc')->select();

		foreach($res as $val){
			$result[] = $val['id'];	
		}		
		return $result;
	}

    public function getQuestionsById($ids,$order=null){
        if(empty($ids)) return false;
        if(empty($order)) $order = 'id asc';
        return Db::name($this->name)->where('id',['in',$ids])->order($order)->select();
    }

    /**
     * @param null $arg
     * @param null $filed
     * @param null $left_join
     * @return bool|string
     */
    public function getQuestionsInfoByArgs($arg = null,$filed = null,$left_join = null,$db_name = 'ex_questions')
    {
        if(empty($arg)) return false;
        if (empty($filed)) $filed = '*';
        if (empty($left_join)) $left_join = '';
        $sql ='select '.$filed.' from '.$db_name.' '.$left_join.' where '.$arg;
        $result = $this->query($sql);
        if ($result){
            return $result;
        }else{
            return false;
        }
    }

    public function getQuestionNumBySubjectId($SubjectId,$p_dbs = 1){
        $Questype = new \app\common\model\Questype();
        $QuestionsModel = new \app\common\model\Questions();
        $Subject = new \app\common\model\Subject();

        /* 获取科目绑定的题型配置 */
        $questtype_arr = $Subject->getSubjectQuestType($SubjectId);
	
        //根据科目和题型获取 试题数目
        $questtype_arr = implode(',',$questtype_arr);
        if ($p_dbs==1){
            $db_name = 'ex_questions';
        }else{
            $db_name = 'ex_question_db';
        }
        $child_plaform = getChildAdminRegByPlaformId($this->plaform);
		 $plaform_parentid = Db::name('plaform')->field('parentid')->where(['admin_reg'=>$_SESSION["think"]["reg"]])->find();
		if($plaform_parentid['parentid']){
			
			$upadmin = Db::name('plaform')->field('admin_reg')->where(['id'=>$plaform_parentid['parentid']])->find();
			$child_plaform[] = $upadmin['admin_reg'];
		}
        $cplaform = '1';
        if (count($child_plaform)>1){
            foreach ($child_plaform as $kc=>$kv)
            {
                $cplaform .=",'".$kv."' ";
            }
        }else{
            $cplaform = implode(',',$child_plaform);
            $cplaform = "'".$cplaform."'";
        }

        $arg = " {$db_name}.q_typeid in ($questtype_arr) and {$db_name}.admin_reg in ({$cplaform})  and {$db_name}.q_knowsid in (select id from ex_knows where k_subjectid='{$SubjectId}')  GROUP BY {$db_name}.q_typeid";
        $field = " {$db_name}.q_typeid,count({$db_name}.id) as num ";
        $left_join = " left join ex_knows on ex_knows.id={$db_name}.id " ;
        $questionNum = $QuestionsModel->getQuestionsInfoByArgs($arg,$field,$left_join,$db_name);
        //根据科目和题型获取 试题数目 end
        $quest_type = $Questype->getQuesTypesById($questtype_arr);
        if (empty($questionNum)) {
            $questionNum = [[]];
        }else{
            foreach ($questionNum as &$val){
                foreach ($quest_type as &$value){
                    if ($val['q_typeid']==$value['id']){
                        $val['type_name'] = $value['type'];
                    }
                }
            }
        }
        return [$questionNum,$quest_type];
    }

    public function getQuestionsNum($qbank_id,$type_id,$know_3,$secs_id,$p_cid){
        $Qbank = new \app\common\model\Qbank();
        //根据题库ID 获取是否 顶级题库
        $parentid = $Qbank->getListByArgOne(['id'=>$qbank_id],'parentid');
        //根据科目和题型获取 试题数目
        if ($parentid['parentid']==0){
            $db_name = 'ex_questions';
        }else{
            $db_name = 'ex_question_db';
        }
        $child_plaform = getChildAdminRegByPlaformId($this->plaform);
		 $plaform_parentid = Db::name('plaform')->field('parentid')->where(['admin_reg'=>$_SESSION["think"]["reg"]])->find();
		if($plaform_parentid['parentid']){
			
			$upadmin = Db::name('plaform')->field('admin_reg')->where(['id'=>$plaform_parentid['parentid']])->find();
			$child_plaform[] = $upadmin['admin_reg'];
		}
        $cplaform ='1';
        if (count($child_plaform)>1){
            foreach ($child_plaform as $kc=>$kv)
            {
                $cplaform .=",'".$kv."' ";
            }
        }else{
            $cplaform = implode(',',$child_plaform);
            $cplaform = "'".$cplaform."'";
        }
        $condition = " {$db_name}.admin_reg in ({$cplaform}) and q_qbankid = {$qbank_id}";
        if ($type_id!=0) $condition .=" AND {$db_name}.q_typeid = {$type_id} ";
        if ($know_3!=0) $condition .=" AND {$db_name}.q_knowsid = {$know_3} ";
        if ($secs_id!=0) $condition .=" AND {$db_name}.q_sectionid = {$secs_id} ";
        if ($p_cid!=0) $condition .=" AND {$db_name}.q_subjectid = {$p_cid} ";
        $condition .= "  GROUP BY {$db_name}.q_typeid";
        $field = " {$db_name}.q_typeid,count({$db_name}.id) as num ";
        $aql = "SELECT {$field} FROM {$db_name} WHERE {$condition}";
        $result = $this->query($aql);
        return $result;
    }
	
	public function getListByArgOne(array $arg=null,$field='*'){
        if (!is_array($arg))return false;
        $arg = $this->where($arg)->field($field)->find();
        return $arg;
    }
}
